package com.aitaoxue.palx;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;

import org.apache.http.HttpException;

import com.aitaoxue.palx.util.TLog;
import com.aitaoxue.palx.util.UIHelper;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

public class AppException extends Exception implements UncaughtExceptionHandler {

	private final static boolean Debug = false;

	// �쳣����
	public final static byte TYPE_NETWORK = 0x01;
	public final static byte TYPE_SOCKET = 0x02;
	public final static byte TYPE_HTTP_CODE = 0x03;
	public final static byte TYPE_HTTP_ERROR = 0x04;
	public final static byte TYPE_IO = 0x05;
	public final static byte TYPE_RUN = 0x06;
	public final static byte TYPE_JSON = 0x07;
	public final static byte TYPE_FILENOTFOUND = 0x08;

	private byte type;
	private int code;

	private Thread.UncaughtExceptionHandler mDefaultHandler;
	private AppContext mContext;

	private AppException(Context context) {
		this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
		this.mContext = (AppContext) context;
	}

	private AppException(byte type, int code, Exception excp) {
		super(excp);
		this.type = type;
		this.code = code;
		if (Debug) {
			saveErrorLog(excp);
		}
	}

	public int getCode() {
		return code;
	}

	public byte getType() {
		return type;
	}

	public void saveErrorLog(Exception excp) {
		String errorlog = "errorlog.txt";
		String savePath = "";
		String logFilePath = "";
		FileWriter fw = null;
		PrintWriter pw = null;

		try {
			String storageState = Environment.getExternalStorageState();
			if (storageState.equals(Environment.MEDIA_MOUNTED)) {
				savePath = Environment.getExternalStorageDirectory()
						.getAbsolutePath() + "Palx/log";
				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdirs();
				}
				logFilePath = savePath + errorlog;
			}

			if (logFilePath == "") {
				return;
			}

			File logFile = new File(logFilePath);
			if (!logFile.exists()) {
				logFile.createNewFile();
			}

			fw = new FileWriter(logFile, true);
			pw = new PrintWriter(fw);
			pw.println("--------------------" + (new Date().toLocaleString())
					+ "---------------------");
			excp.printStackTrace(pw);
			pw.close();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (pw != null)
				pw.close();
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public static AppException http(int code) {
		return new AppException(TYPE_HTTP_CODE, code, null);
	}

	public static AppException http(Exception e) {
		return new AppException(TYPE_HTTP_ERROR, 0, e);
	}

	public static AppException socket(Exception e) {
		return new AppException(TYPE_SOCKET, 0, e);
	}

	public static AppException file(Exception e) {
		return new AppException(TYPE_FILENOTFOUND, 0, e);
	}

	public static AppException io(Exception e) {
		return io(e, 0);
	}

	public static AppException io(Exception e, int code) {
		if (e instanceof UnknownHostException || e instanceof ConnectException) {
			return new AppException(TYPE_HTTP_ERROR, code, e);
		} else if (e instanceof IOException) {
			return new AppException(TYPE_IO, code, e);
		}
		return run(e);
	}

	public static AppException json(Exception e) {
		return new AppException(TYPE_JSON, 0, e);
	}

	public static AppException network(Exception e) {
		if (e instanceof UnknownHostException || e instanceof ConnectException) {
			return new AppException(TYPE_NETWORK, 0, e);
		} else if (e instanceof HttpException) {
			return http(e);
		} else if (e instanceof SocketException) {
			return socket(e);
		}
		return http(e);
	}

	public static AppException run(Exception e) {
		return new AppException(TYPE_RUN, 0, e);
	}

	public static AppException getAppExceptionHandler(Context context) {
		return new AppException(context.getApplicationContext());
	}

	@Override
	public void uncaughtException(Thread arg0, Throwable arg1) {
		if (!handleException(arg1) && mDefaultHandler != null) {
			mDefaultHandler.uncaughtException(arg0, arg1);
		}
	}

	private boolean handleException(final Throwable ex) {
		if (ex == null) {
			return false;
		}

		if (mContext == null) {
			return false;
		}

		final String crashReport = getCrashReport(AppContext.getInstance(), ex);
		new Thread() {
			public void run() {
				Looper.prepare();
				Toast.makeText(mContext, "出现未捕获异常", Toast.LENGTH_LONG);
				TLog.log("Test", crashReport);

//				UIHelper.sendAppCrashReport(AppContext.getInstance(),
//						crashReport);

				Looper.loop();
			}
		}.start();
		return true;
	}

	private String getCrashReport(Context context, Throwable ex) {
		PackageInfo pinfo = ((AppContext) context.getApplicationContext())
				.getPackageInfo();
		StringBuffer exceptionStr = new StringBuffer();
		exceptionStr.append("version: " + pinfo.versionName + "("
				+ pinfo.versionCode + ")\n");
		exceptionStr.append("API Level: " + android.os.Build.VERSION.SDK_INT
				+ "\n");
		exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE
				+ "(" + android.os.Build.MODEL + ")\n");
		exceptionStr.append("异常信息:\n");
		exceptionStr.append("Exception: " + ex.getMessage() + "\n\n\n");
		exceptionStr.append("堆栈信息:\n");
		StackTraceElement[] elements = ex.getStackTrace();
		for (int i = 0; i < elements.length; i++) {
			exceptionStr.append(elements[i].toString() + "\n");
		}
		return exceptionStr.toString();
	}

}
